import React, { useState, useEffect, useCallback } from 'react';
import LazyLoad from 'react-lazyload';
import './index.css';

interface Product {
  id: string;
  name: string;
  price: number;
  type: string;
  package: string;
  images: string[];
}

interface ListProps {
  products: Product[];
  onLoadMore: () => void;
  hasMore: boolean;
  loading: boolean;
}

const PAGE_SIZE = 10;

const ProductList: React.FC<ListProps> = ({ products, onLoadMore, hasMore, loading }) => {
  const [displayedProducts, setDisplayedProducts] = useState<Product[]>([]);
  const [currentPage, setCurrentPage] = useState(1);

  // 处理触底加载
  const handleScroll = useCallback(() => {
    const scrollHeight = document.documentElement.scrollHeight;
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight;

    // 距离底部100px时触发加载
    if (scrollHeight - scrollTop - clientHeight < 100 && !loading && hasMore) {
      onLoadMore();
    }
  }, [loading, hasMore, onLoadMore]);

  // 监听滚动事件
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [handleScroll]);

  // 更新显示的商品列表
  useEffect(() => {
    const end = currentPage * PAGE_SIZE;
    setDisplayedProducts(products.slice(0, end));
  }, [products, currentPage]);

  return (
    <div className="product-list">
      {displayedProducts.map((product) => (
        <div 
          key={product.id} 
          className="product-item"
        >
          <LazyLoad 
            height={160} 
            offset={500}
            resize={true}
            placeholder={
              <div className="image-placeholder" />
            }
          >
            <div className="product-image-container">
              <img 
                src={product.images[0]} 
                alt={product.name}
                className="product-image"
                onError={(e) => {
                  const target = e.target as HTMLImageElement;
                  target.src = 'https://via.placeholder.com/300x300?text=商品图片';
                }}
              />
            </div>
          </LazyLoad>
          <div className="product-info">
            <h4 className="product-name">{product.name}</h4>
            <div className="product-price">¥{product.price}</div>
            <div className="product-meta">
              <span>{product.type}</span>
              <span>{product.package}</span>
            </div>
          </div>
        </div>
      ))}
      {loading && (
        <div className="loading-more">
          <div className="loading-spinner" />
          加载中...
        </div>
      )}
      {!hasMore && displayedProducts.length > 0 && (
        <div className="no-more">没有更多了</div>
      )}
    </div>
  );
};

export default ProductList;
